
package com.hazelcast.internal.config.override;

import com.hazelcast.internal.util.StringUtil;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toMap;

/**
 * A utility class converting raw input properties into valid config entries.
 */
class EnvVariablesConfigParser {
    private static final List<String> EXCLUDED_ENTRIES = Arrays.asList("HZ_HOME", "HZ_LICENSE_KEY", "HZ_PHONE_HOME_ENABLED", "HZ_CP_MOUNT");

    private final String prefix;
    private final String rootNode;

    EnvVariablesConfigParser(String prefix, String rootNode) {
        this.prefix = prefix;
        this.rootNode = rootNode;
    }

    static EnvVariablesConfigParser client() {
        return new EnvVariablesConfigParser("HZCLIENT_", "hazelcast-client");
    }

    static EnvVariablesConfigParser member() {
        return new EnvVariablesConfigParser("HZ_", "hazelcast");
    }

    Map<String, String> parse(Map<String, String> env) {
        return env.entrySet().stream().filter(e -> !EXCLUDED_ENTRIES.contains(e.getKey().replace(" ", ""))).filter(e -> e.getKey().startsWith(prefix)).collect(toMap(this::processKey, Map.Entry::getValue));
    }

    private String processKey(Map.Entry<String, String> e) {
        // we convert keys to lowercase for processing later; we parse the keys to find the correct
        //  configuration objects to override, and all of our configuration keys are lowercase
        return StringUtil.lowerCaseInternal(e.getKey().replaceFirst(prefix, rootNode + ".").replace("_", ".").replace(" ", ""));
    }
}
